import React, { useState } from 'react';
import {
  Search,
  CheckCircle,
  AlertTriangle,
  Loader2,
  Shield,
  ShieldCheck,
  ExternalLink,
  Cpu,
  Server,
  ChevronRight,
  Sparkles,
  Verified,
  Tag
} from 'lucide-react';
import { ToolViewProps } from '../types';
import { formatTimestamp, getToolTitle } from '../utils';
import { cn, truncateString } from '@/lib/utils';
import { extractSearchMcpServersData, McpServerResult } from './_utils';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button } from '@/components/ui/button';
import { ScrollArea } from "@/components/ui/scroll-area";
import { LoadingState } from '../shared/LoadingState';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/components/ui/tooltip";

export function SearchMcpServersToolView({
  toolCall,
  toolResult,
  assistantTimestamp,
  toolTimestamp,
  isSuccess = true,
  isStreaming = false,
}: ToolViewProps) {
  // All hooks must be called unconditionally at the top
  const [expandedResults, setExpandedResults] = useState<Record<number, boolean>>({});

  // Defensive check - ensure toolCall is defined
  if (!toolCall) {
    console.warn('SearchMcpServersToolView: toolCall is undefined. Tool views should use structured props.');
    return null;
  }

  const name = toolCall.function_name.replace(/_/g, '-').toLowerCase();
  const toolTitle = getToolTitle(name);

  const {
    query,
    results,
    limit,
    actualIsSuccess,
    actualToolTimestamp,
    actualAssistantTimestamp
  } = extractSearchMcpServersData(
    toolCall,
    toolResult,
    isSuccess,
    toolTimestamp,
    assistantTimestamp
  );

  const getAuthSchemeColor = (authSchemes: string[]) => {
    if (authSchemes?.includes('OAUTH2')) {
      return 'bg-emerald-100 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-800';
    } else if (authSchemes?.includes('API_KEY')) {
      return 'bg-blue-100 text-blue-700 border-blue-200 dark:bg-blue-900/20 dark:text-blue-300 dark:border-blue-800';
    } else if (authSchemes?.includes('BEARER_TOKEN')) {
      return 'bg-purple-100 text-purple-700 border-purple-200 dark:bg-purple-900/20 dark:text-purple-300 dark:border-purple-800';
    } else {
      return 'bg-gray-100 text-gray-700 border-gray-200 dark:bg-gray-900/20 dark:text-gray-300 dark:border-gray-800';
    }
  };

  const getAuthSchemeIcon = (authSchemes: string[]) => {
    if (authSchemes?.includes('OAUTH2')) {
      return ShieldCheck;
    } else {
      return Shield;
    }
  };

  const getPrimaryAuthScheme = (authSchemes: string[]) => {
    if (authSchemes?.includes('OAUTH2')) return 'OAuth2';
    if (authSchemes?.includes('API_KEY')) return 'API Key';
    if (authSchemes?.includes('BEARER_TOKEN')) return 'Bearer Token';
    return authSchemes?.[0] || 'Unknown';
  };

  return (
    <Card className="gap-0 flex border-0 shadow-none p-0 py-0 rounded-none flex-col h-full overflow-hidden bg-card">
      <CardHeader className="h-14 bg-zinc-50/80 dark:bg-zinc-900/80 backdrop-blur-sm border-b p-2 px-4 space-y-2">
        <div className="flex flex-row items-center justify-between">
          <div className="flex items-center gap-2">
            <div className="relative p-2 rounded-xl bg-gradient-to-br from-purple-500/20 to-purple-600/10 border border-purple-500/20">
              <Search className="w-5 h-5 text-purple-500 dark:text-purple-400" />
            </div>
            <div>
              <CardTitle className="text-base font-medium text-zinc-900 dark:text-zinc-100">
                {toolTitle}
              </CardTitle>
            </div>
          </div>

          {!isStreaming && (
            <Badge
              variant="secondary"
              className={cn(
                "text-xs font-medium",
                actualIsSuccess
                  ? "bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-900/20 dark:text-emerald-300 dark:border-emerald-800"
                  : "bg-red-50 text-red-700 border-red-200 dark:bg-red-900/20 dark:text-red-300 dark:border-red-800"
              )}
            >
              {actualIsSuccess ? (
                <CheckCircle className="h-3 w-3 " />
              ) : (
                <AlertTriangle className="h-3 w-3 " />
              )}
              {results.length} {results.length === 1 ? 'result' : 'results'}
            </Badge>
          )}
        </div>
      </CardHeader>

      <CardContent className="p-0 h-full flex-1 overflow-hidden relative">
        {isStreaming ? (
          <LoadingState
            icon={Search}
            iconColor="text-purple-500 dark:text-purple-400"
            bgColor="bg-gradient-to-b from-purple-100 to-purple-50 shadow-inner dark:from-purple-800/40 dark:to-purple-900/60 dark:shadow-purple-950/20"
            title="Searching MCP servers"
            filePath={query ? `"${query}"` : undefined}
            showProgress={true}
          />
        ) : results.length > 0 ? (
          <ScrollArea className="h-full w-full">
            <div className="p-4 space-y-3">
              {results.map((result: McpServerResult, index: number) => {
                const AuthIcon = getAuthSchemeIcon(result.auth_schemes);
                const isExpanded = expandedResults[index];
                const hasOAuth = result.auth_schemes?.includes('OAUTH2');
                
                return (
                  <div
                    key={index}
                    className="group relative p-4 border rounded-xl"
                  >
                    <div className="flex items-start gap-3">
                      <div className="relative flex-shrink-0">
                        <div className="w-12 h-12 rounded-xl overflow-hidden bg-muted/50 border flex items-center justify-center">
                          {result.logo_url ? (
                            <img
                              src={result.logo_url}
                              alt={`${result.name} logo`}
                              className="w-8 h-8 object-cover"
                              onError={(e) => {
                                const target = e.target as HTMLImageElement;
                                target.style.display = 'none';
                                const parent = target.parentElement;
                                if (parent) {
                                  parent.innerHTML = `<div class="w-full h-full flex items-center justify-center"><svg class="w-6 h-6 text-zinc-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clip-rule="evenodd" /></svg></div>`;
                                }
                              }}
                            />
                          ) : (
                            <Server className="w-6 h-6 text-zinc-400" />
                          )}
                        </div>
                        {hasOAuth && (
                          <div className="absolute -top-1 -right-1">
                            <div className="bg-emerald-500 rounded-full p-1">
                              <Verified className="w-3 h-3 text-white" />
                            </div>
                          </div>
                        )}
                      </div>

                      <div className="flex-1 min-w-0">
                        <div className="flex items-start justify-between gap-2 mb-2">
                          <div className="flex-1 min-w-0">
                            <div className="flex items-center gap-2 mb-1">
                              <h3 className="font-semibold text-zinc-900 dark:text-zinc-100 truncate">
                                {result.name}
                              </h3>
                              {hasOAuth && (
                                <TooltipProvider>
                                  <Tooltip>
                                    <TooltipTrigger>
                                      <div className="flex items-center">
                                        <Sparkles className="w-4 h-4 text-emerald-500" />
                                      </div>
                                    </TooltipTrigger>
                                    <TooltipContent>
                                      <p>OAuth2 supported</p>
                                    </TooltipContent>
                                  </Tooltip>
                                </TooltipProvider>
                              )}
                            </div>
                            <p className="text-sm text-zinc-600 dark:text-zinc-400 font-mono">
                              {result.toolkit_slug}
                            </p>
                          </div>
                          <div className="flex items-center gap-2">
                            <Badge
                              variant="outline"
                              className={cn("text-xs font-medium", getAuthSchemeColor(result.auth_schemes))}
                            >
                              <AuthIcon className="w-3 h-3 " />
                              {getPrimaryAuthScheme(result.auth_schemes)}
                            </Badge>
                          </div>
                        </div>
                        <p className={cn(
                          "text-sm text-zinc-600 dark:text-zinc-300 leading-relaxed mb-3",
                        )}>
                          {result.description}
                        </p>
                        <div className="flex items-center justify-between">
                          <div className="flex items-center gap-2">
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>
          </ScrollArea>
        ) : (
          <div className="flex flex-col items-center justify-center h-full py-8 px-6">
            <div className="text-center w-full max-w-xs">
              <div className="w-16 h-16 rounded-xl mx-auto mb-4 flex items-center justify-center bg-zinc-100 dark:bg-zinc-800 border border-zinc-200 dark:border-zinc-700">
                <Search className="h-8 w-8 text-zinc-400" />
              </div>
              <h3 className="text-base font-medium text-zinc-900 dark:text-zinc-100 mb-2">
                No MCP servers found
              </h3>
              <p className="text-sm text-zinc-500 dark:text-zinc-400">
                {query ? `No results found for "${query}"` : 'Try searching with different keywords'}
              </p>
            </div>
          </div>
        )}
      </CardContent>
    </Card>
  );
} 